package com.cjlgb.design.common.core.cfgbean;

import com.cjlgb.design.common.core.handler.GlobalExceptionHandler;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.client.RestTemplate;

/**
 * @author WFT
 * @date 2019/5/18
 * description:全局配置类
 */
@Configuration
@EnableAsync
@EnableCaching
public class GlobalConfiguration {

    /**
     * http 工具类
     * @return RestTemplate
     */
    @Bean(name = "restTemplate")
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

    /**
     * @return 全局异常处理类
     */
    @Bean(value = "globalExceptionHandler")
    public GlobalExceptionHandler globalExceptionHandler(){
        return new GlobalExceptionHandler();
    }

    /**
     * 配置反序列化时,禁用对日期以时间戳方式输出的特性
     * @return ObjectMapper
     */
    @Bean
    public ObjectMapper serializingObjectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        //  忽略value为null时，key的输出
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        //  禁用对日期以时间戳方式输出的特性
        mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        mapper.registerModule(new JavaTimeModule());
        /*
            序列换成json时,将所有的long变成string
            因为js中得数字类型不能包含所有的java long值
         */
        SimpleModule module = new SimpleModule();
        module.addSerializer(Long.class, ToStringSerializer.instance);
        module.addSerializer(Long.TYPE, ToStringSerializer.instance);
        mapper.registerModule(module);
        return mapper;
    }

}
